<template>
	<div class="tabelContainer">
		<basic-container>
			<el-dialog title="详细信息" :visible.sync="dialogVisible" :modal-append-to-body="false" width="45%" top="20vh">
				<el-table :show-header="false" :data="tableData" border :cell-style="columnStyle" style="width: 100%;">
					<el-table-column width="150" prop="prop1"></el-table-column>
					<el-table-column prop="value1"></el-table-column>
					<el-table-column width="150" prop="prop2"></el-table-column>
					<el-table-column prop="value2"></el-table-column>
				</el-table>
			</el-dialog>
			<avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad" :search.sync="search" @row-click="handleRowClick">
				<!-- 左侧菜单栏自定义 -->
				<template slot="menuLeft">
					<transition name="el-fade-in">
						<el-button v-show="dataSource === '实时数据'" @click="btnRefreshClick()" size='mini' type="primary" icon="el-icon-refresh">刷新倒计时{{ refreshTime }}s</el-button>
					</transition>
					<el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.devicematerialdata_delete" @click="handleDelete">删 除
					</el-button>
				</template>
				<!-- 右侧菜单栏自定义 -->
				<template slot="menuRight">
					<el-radio-group id="data-source-radio" v-model="dataSource" size="mini">
						<el-radio-button label="实时数据"></el-radio-button>
						<el-radio-button label="历史数据"></el-radio-button>
					</el-radio-group>
				</template>
				<!-- 设备查询时间自定义 -->
				<template slot-scope="{disabled,size}" slot="datetimeSearch">
					<div class="search-date">
						<el-date-picker v-model="dateFrom" type="date" size="small" placeholder="开始日期" :picker-options="startPickerOpt" value-format="yyyy-MM-dd"></el-date-picker>
						<div>&nbsp;至&nbsp;</div>
						<el-date-picker v-model="dateTo" type="date" size="small" placeholder="结束日期" :picker-options="endPickerOpt" value-format="yyyy-MM-dd"></el-date-picker>
					</div>
				</template>
				<!-- 设备状态列自定义 -->
				<template slot="diviceStatus" slot-scope="scope">
					<div v-if="scope.row.isWeightAlarm === 1 || scope.row.isBatteryAlarm === 1 || scope.row.isDeviceFailureAlarm === 1" class="status-icon warn-status-icon"></div>
					<div v-else class="status-icon normal-status-icon"></div>
				</template>
				<!-- 设备状态文字自定义 -->
				<template slot="isWeightAlarm" slot-scope="scope">
					<div v-if="scope.row.isWeightAlarm === 1 && scope.row.isWeightAlarmType !== ''" class="warn-status-text">{{scope.row.isWeightAlarmType}}</div>
					<div v-else-if="scope.row.isWeightAlarm === 0 && scope.row.isWeightAlarmType !== ''">{{scope.row.isWeightAlarmType}}</div>
					<div v-else>-</div>
				</template>
				<template slot="isBatteryAlarm" slot-scope="scope">
					<div v-if="scope.row.isBatteryAlarm === 1 && scope.row.isBatteryAlarmType !== ''" class="warn-status-text">{{scope.row.isBatteryAlarmType}}</div>
					<div v-else-if="scope.row.isBatteryAlarm === 0 && scope.row.isBatteryAlarmType !== ''">{{scope.row.isBatteryAlarmType}}</div>
					<div v-else>-</div>
				</template>
				<template slot="weight" slot-scope="scope">
					<div v-if="scope.row.weight === '' || scope.row.weight === null">-</div>
					<div v-else>{{scope.row.weight}}</div>
				</template>
				<template slot="battery" slot-scope="scope">
					<div v-if="scope.row.battery === '' || scope.row.battery === null">-</div>
					<div v-else>{{scope.row.battery}}</div>
				</template>
				<template slot="datetime" slot-scope="scope">
					<div v-if="scope.row.datetime === '' || scope.row.datetime === null">-</div>
					<div v-else>{{scope.row.datetime}}</div>
				</template>
			</avue-crud>
		</basic-container>
	</div>
</template>

<script>
	import {
		getList,
		getCurrentData,
		getDetail,
		add,
		update,
		remove
	} from "@/api/dust/devicematerialdata";
	import {
		mapGetters
	} from "vuex";
	import {
		getStore,
		removeStore
	} from '@/util/store'
	import {
		dateFormat
	} from "@/util/date";

	export default {
		data() {
			return {
				// radio selected
				dataSource: '实时数据',

				// search opt
				search: {},

				// 时间查询
        dateToday: dateFormat(new Date(Date.now()), 'yyyy-MM-dd'),
        dateFrom: dateFormat(new Date(Date.now()), 'yyyy-MM-dd'),
        dateTo: dateFormat(new Date(Date.now()), 'yyyy-MM-dd'),

				// dialog
				dialogVisible: false,
				tableData: [{
						prop1: "设备名称",
						value1: "",
						prop2: "设备厂家名称",
						value2: ""
					},
					{
						prop1: "设备类型",
						value1: "",
						prop2: "终端编号",
						value2: ""
					},
					{
						prop1: "额定重量",
						value1: "",
						prop2: "驾驶员身份证号",
						value2: ""
					},
				],

				// refresh limit time
				refreshTime: 10,
				clock: null,

				// templete data
				form: {},
				query: {},
				loading: true,
				page: {
					pageSize: this.$pageSize,
					currentPage: 1,
					total: 0
				},
				selectionList: [],
				option: {
					defaultSort: {
						prop: 'datetime',
						order: 'descending' // 历史数据按时间倒序排列
					},
					menu: false,
					align: 'center',
					// height: 'auto',
					calcHeight: 30,
					tip: false,
					refreshBtn: true,
					searchShow: true,
					searchMenuSpan: 4,
					border: true,
					index: false,
					viewBtn: true,
					selection: false,
					dialogClickModal: false,
					column: [{
							label: "项目名称",
							prop: "deptInfoId",
							type: "select",
							dicUrl: "/api/squirrel-ficm/deptinfo/getProjectList",
							props: {
								label: "deptName",
								value: "id"
							},
							hide: true,
							search: true,
							searchSpan: 4,
							searchLabelWidth: 75,
							rules: [{
								required: true,
								message: "请输入项目名称，中文",
								trigger: "blur"
							}]
						}, {
							label: "设备名称",
							prop: "deviceName",
							search: true,
							searchSpan: 4,
							searchLabelWidth: 75,
							rules: [{
								required: true,
								message: "请输入设备名称",
								trigger: "blur"
							}],
						},
						{
							label: "设备状态",
							prop: "diviceStatus",
							slot: true,
							rules: [{
								required: true,
								message: "请输入设备状态",
								trigger: "blur"
							}]
						},
						{
							label: "重量报警",
							prop: "isWeightAlarm",
							slot: true,
							rules: [{
								required: true,
								message: "请输入重量报警，1：报警，0：正常",
								trigger: "blur"
							}]
						},
						{
							label: "电池电量低",
							prop: "isBatteryAlarm",
							slot: true,
							rules: [{
								required: true,
								message: "请输入电池电量低，1：报警，0：正常",
								trigger: "blur"
							}]
						},
						{
							label: "当前重量（吨）",
							prop: "weight",
							slot: true,
							rules: [{
								required: true,
								message: "请输入当前重量，单位：吨",
								trigger: "blur"
							}]
						},
						{
							label: "电池电量（%）",
							prop: "battery",
							slot: true,
							rules: [{
								required: true,
								message: "请输入电池电量，单位：%",
								trigger: "blur"
							}]
						},
						{
							label: "数据采集时间",
							prop: "datetime",
							type: "datetime",
							format: "yyyy-MM-dd HH:mm:ss",
							valueFormat: "yyyy-MM-dd HH:mm:ss",
							width: 150,
							slot: true,
							search: true,
							searchslot: true,
							searchSpan: 7,
							searchLabelWidth: 100,
							rules: [{
								required: true,
								message: "请输入数据采集时间",
								trigger: "blur"
							}]
						},
					]
				},
				data: [],
			};
		},
		watch: {
			dataSource(val) {
				if(val === '实时数据') {
					this.page.total = 0;
					// 实时数据不显示时间搜索，注意索引的修改
					this.option.column[7].search = false;
					this.onLoad(this.page);
					this.refreshCountDown();
				} else if(val === '历史数据') {
					this.option.column[7].search = true;
					this.onLoad(this.page);
				} else {
					this.data = [];
				}
			},
			dateFrom() {
				if(this.dateFrom) {
					let startDate = new Date(this.dateFrom)
					let endDate = new Date(this.dateTo)
					if(startDate.getTime() > endDate.getTime()) {
						this.dateTo = this.dateFrom
					} else if(endDate.getTime() > startDate.getTime() + 7 * 24 * 60 * 60 * 1000) {
						startDate.setTime(startDate.getTime() + 7 * 24 * 60 * 60 * 1000)
						this.dateTo = dateFormat(new Date(startDate), 'yyyy-MM-dd')
					}
				}
			},
			dateTo() {
				if(this.dateTo) {
					let startDate = new Date(this.dateFrom)
					let endDate = new Date(this.dateTo)
					if(startDate.getTime() > endDate.getTime()) {
						this.dateFrom = this.dateTo
					} else if(endDate.getTime() - 7 * 24 * 60 * 60 * 1000 > startDate.getTime()) {
						endDate.setTime(endDate.getTime() - 7 * 24 * 60 * 60 * 1000)
						this.dateFrom = dateFormat(new Date(endDate), 'yyyy-MM-dd')
					}
				}
			},
		},
		beforeDestroy() {
			removeStore({
				name: 'unloading'
			})
		},
		mounted: function() {
			let unloading = getStore({
				name: 'unloading'
			})
			if(unloading) {
				this.dataSource = '历史数据';
				this.onLoad(this.page, this.query);
			}
			// 暴露this
			window.vue = this;
		},
		created: function() {
			this.refreshCountDown();
			if(this.dataSource === '实时数据') this.option.column[7].search = false;
		},
		destroyed: function() {
			// 页面销毁后清除计时器
			window.clearInterval(this.clock);
		},
		computed: {
			...mapGetters(["permission"]),
			permissionList() {
				return {
					addBtn: this.vaildData(this.permission.devicematerialdata_add, false),
					viewBtn: this.vaildData(this.permission.devicematerialdata_view, false),
					delBtn: this.vaildData(this.permission.devicematerialdata_delete, false),
					editBtn: this.vaildData(this.permission.devicematerialdata_edit, false)
				};
			},
			ids() {
				let ids = [];
				this.selectionList.forEach(ele => {
					ids.push(ele.id);
				});
				return ids.join(",");
			}
		},
		methods: {
			/**
			 * 刷新倒计时
			 */
			refreshCountDown() {
				if(this.clock !== null) { // 如果存在倒计时，清空
					window.clearInterval(this.clock);
				}
				// 重新设定时间和interval
				this.refreshTime = 10;
				this.clock = window.setInterval(() => {
					this.refreshTime--;
					if(this.refreshTime <= 0) {
						window.clearInterval(this.clock);
						if(this.dataSource === '实时数据') {
							this.onLoad(this.page);
						}
						this.refreshCountDown();
					}
				}, 1000)
			},
			/**
			 * 实时数据刷新按钮响应函数
			 */
			btnRefreshClick() {
				this.onLoad(this.page);
				this.refreshCountDown();
			},
			rowSave(row, done, loading) {
				add(row).then(() => {
					this.onLoad(this.page);
					this.$message({
						type: "success",
						message: "操作成功!"
					});
					done();
				}, error => {
					loading();
					window.console.log(error);
				});
			},
			rowUpdate(row, index, done, loading) {
				update(row).then(() => {
					this.onLoad(this.page);
					this.$message({
						type: "success",
						message: "操作成功!"
					});
					done();
				}, error => {
					loading();
					console.log(error);
				});
			},
			rowDel(row) {
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(row.id);
					})
					.then(() => {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
					});
			},
			handleDelete() {
				if(this.selectionList.length === 0) {
					this.$message.warning("请选择至少一条数据");
					return;
				}
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(this.ids);
					})
					.then(() => {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
						this.$refs.crud.toggleSelection();
					});
			},
			beforeOpen(done, type) {
				if(["edit", "view"].includes(type)) {
					getDetail(this.form.id).then(res => {
						this.form = res.data.data;
					});
				}
				done();
			},

			/**
			 * 搜索重置
			 */
			searchReset() {
				this.query = {};
				// 自定义时间查询，手动清空输入框
				this.dateFrom = '';
				this.dateTo = '';
				this.onLoad(this.page);
			},

			/**
			 * 搜索
			 * @param {Object} params
			 * @param {Object} done
			 */
			searchChange(params, done) {
				this.query = params;
				this.page.currentPage = 1;
				this.onLoad(this.page, params);
				done();
			},
			selectionChange(list) {
				this.selectionList = list;
			},
			selectionClear() {
				this.selectionList = [];
				this.$refs.crud.toggleSelection();
			},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
			},

			/**
			 * 行单击
			 * @param {Object} row
			 * @param {Object} event
			 * @param {Object} column
			 */
			handleRowClick(row, event, column) {
				var col1 = ["deviceName", "deviceType", "limitWeight"]; // 设备名称 设备类型 额定重量
				var col2 = ["ownerName", "deviceId", "接口没给"]; // 设备厂家名称 终端编号 驾驶员身份证
				for(var i = 0, len = this.tableData.length; i < len; i++) {
					this.$set(this.tableData[i], 'value1', row[col1[i]]);
					this.$set(this.tableData[i], 'value2', row[col2[i]]);
				}
				this.dialogVisible = true;
			},

			/**
			 * 刷新表单
			 */
			refreshChange() {
				this.onLoad(this.page, this.query);
			},

			/**
			 * 加载表单
			 */
			onLoad(page, params = {}) {
				this.loading = true;
				if(this.dataSource === '实时数据') { // 获取实时数据
					getCurrentData(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
						const data = res.data.data;
						this.data = data;
						this.loading = false;
						this.selectionClear();
					})
				} else { // 获取历史数据
					// 自定义查询，手动添加键值对
					this.query['start'] = this.dateFrom;
					this.query['end'] = this.dateTo;
					getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
						const data = res.data.data;
						this.page.total = data.total;
						this.data = data.records;
						this.loading = false;
						this.selectionClear();
					});
				}
			},
		}
	};
</script>

<style scoped>
	#data-source-radio {
		margin-right: 10px;
	}

	.search-date {
		display: flex;
		height: 33px;
		line-height: 33px;
	}

	.status-icon {
		width: 18px;
		height: 18px;
		margin: 0 auto;
		border-radius: 50%;
	}

	.warn-status-icon {
		background-color: rgba(245, 108, 108, 1.0);
	}

	.normal-status-icon {
		background-color: rgba(103, 194, 58, 1.0);
	}

	.warn-status-text {
		color: rgba(245, 108, 108, 1.0);
	}

	.normal-status-text {
		color: rgba(42, 130, 228, 1);
	}
</style>
